// 用户服务 - 处理用户信息管理相关操作
import axios from 'axios'

// 创建axios实例用于用户服务
const userApiClient = axios.create({
  baseURL: '/api', // 后端API基础路径（通过代理）
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器 - 为用户相关请求添加token
userApiClient.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
userApiClient.interceptors.response.use(
  response => {
    return response.data // 直接返回响应数据
  },
  error => {
    const errorMessage = error.response?.data?.msg || error.message || '请求失败'
    console.error('用户API请求错误:', errorMessage)
    throw new Error(errorMessage)
  }
)

class UserService {
  constructor() {
    this.apiClient = userApiClient
  }

  // 获取用户信息
  async getUserInfo() {
    return this.apiClient({
      url: '/v1/user/info',
      method: 'GET'
    })
  }

  // 更新用户信息
  async updateUserInfo(userData) {
    return this.apiClient({
      url: '/v1/user/update',
      method: 'POST',
      data: userData
    })
  }

  // 上传用户头像
  async uploadAvatar(formData) {
    return this.apiClient({
      url: '/v1/user/avatar',
      method: 'POST',
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      data: formData
    })
  }

  // 修改密码
  async changePassword(oldPassword, newPassword) {
    return this.apiClient({
      url: '/v1/user/change-password',
      method: 'POST',
      data: { oldPassword, newPassword }
    })
  }

  // 设置日记隐私
  async setDiaryPrivacy(privacySettings) {
    return this.apiClient({
      url: '/v1/user/diary-privacy',
      method: 'POST',
      data: privacySettings
    })
  }

  // 获取日记隐私设置
  async getDiaryPrivacy() {
    return this.apiClient({
      url: '/v1/user/diary-privacy',
      method: 'GET'
    })
  }

  // 设置二次密码（用于加密日记）
  async setDiaryPassword(password) {
    return this.apiClient({
      url: '/v1/user/diary-password',
      method: 'POST',
      data: { password }
    })
  }

  // 验证二次密码
  async verifyDiaryPassword(password) {
    return this.apiClient({
      url: '/v1/user/diary-password/verify',
      method: 'POST',
      data: { password }
    })
  }

  // 获取用户统计数据
  async getUserStats() {
    return this.apiClient({
      url: '/v1/user/stats',
      method: 'GET'
    })
  }

  // 更新匿名倾诉设置
  async updateAnonymousConfession(enabled) {
    return this.apiClient({
      url: '/v1/user/anonymous-confession',
      method: 'POST',
      data: { enabled }
    })
  }

  // 清除本地存储的用户数据
  clearUserData() {
    localStorage.removeItem('user')
    localStorage.removeItem('privacySettings')
    localStorage.removeItem('diaryPasswordVerified')
  }

  // 从本地存储加载用户设置
  loadLocalSettings() {
    try {
      const settings = localStorage.getItem('privacySettings')
      return settings ? JSON.parse(settings) : {
        diaryPrivacy: 'private',
        anonymousConfession: false,
        dataVisible: true
      }
    } catch (error) {
      console.error('加载本地设置失败:', error)
      return {
        diaryPrivacy: 'private',
        anonymousConfession: false,
        dataVisible: true
      }
    }
  }

  // 保存用户设置到本地存储
  saveLocalSettings(settings) {
    try {
      localStorage.setItem('privacySettings', JSON.stringify(settings))
      return true
    } catch (error) {
      console.error('保存本地设置失败:', error)
      return false
    }
  }
}

// 导出单例实例
const userService = new UserService()
export default userService